// stores/useCategoryStore.js
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { getCategoryAPI } from '@/apis/layout'

export const useCategoryStore = defineStore('category', () => {
  const categoryList = ref([]) // 所有一级分类（排除ALL_CATEGORIES）
  const allCategories = ref([]) // 完整树形结构（包含ALL_CATEGORIES）
  const isLoaded = ref(false)

  const getCategory = async () => {
    if (isLoaded.value) return

    try {
      const res = await getCategoryAPI()
      const treeData = buildCategoryTree(res.data)

      // 分离 "ALL_CATEGORIES" 和普通一级分类
      const allCat = treeData.find(item => item.name === 'ALL_CATEGORIES') || {}
      const normalCategories = treeData
        .filter(item => item.name !== 'ALL_CATEGORIES') // 排除总分类
        .sort((a, b) => a.sort - b.sort) // 按后端sort字段排序（升序：sort越小越靠前）

      allCategories.value = treeData
      categoryList.value = normalCategories // 普通一级分类（已排序）
      isLoaded.value = true
    } catch (error) {
      console.error('获取分类数据失败:', error)
    }
  }

  // 树形结构构建（保留你的逻辑，优化字段检查）
  const buildCategoryTree = (categories) => {
    if (!Array.isArray(categories)) return []

    const topLevelCategories = categories.filter(cat =>
      cat.parentId === null || cat.parentId === 1
    )

    const buildChildren = (parent) => {
      // 查找子分类时增加空值判断，避免报错
      const children = categories.filter(cat =>
        cat?.parentId !== undefined && cat.parentId === parent.id
      ).sort((a, b) => a.sort - b.sort) // 子分类也按sort排序

      children.forEach(child => buildChildren(child))
      parent.children = children || []
      parent.goods = [] // 初始化推荐商品数组
    }

    topLevelCategories.forEach(category => buildChildren(category))
    return topLevelCategories
  }

  const resetLoadState = () => {
    isLoaded.value = false
    categoryList.value = []
    allCategories.value = []
  }

  return {
    categoryList, // 普通一级分类（已排序，无ALL_CATEGORIES）
    allCategories, // 完整数据（含ALL_CATEGORIES）
    getCategory,
    resetLoadState
  }
})